const fs = require('fs');

const options = {
    key: fs.readFileSync('./cert/server.key'),
    cert: fs.readFileSync('./cert/server.pem')
}
const express = require('express')
const app = express()
const serveIndex = require('serve-index');
const uuid = require("uuid");
const {Socket} = require("engine.io");
const {json} = require("express");

function serveIndexFilter(filename, index, list, path) {
    console.log("serveIndexFilter->", filename, index, list, path)
    const fileExtension = filename.split('.').pop().toLowerCase()
    if (fileExtension === "html") {
        return filename
    } else {
        return null
    }
}

app.use(serveIndex('./public', {
    icons: true,
    filter: serveIndexFilter
}));
app.use(express.static('./public'));
const server = require('https').createServer(options, app);

const ioServer = require('socket.io')(server, {
    cors: {
        // origin: "https://localhost:8089",
        // methods: ["GET", "POST"],
        credentials: false
    }
});

const socketServer = ioServer.of("/srs")

const clientWebrtcMap = new Map();

socketServer.on('connection', client => {
    const token = client.handshake.query.token;
    console.log("已连接:",client.id,token)
    clientWebrtcMap.set(client.id,client)

    client.on("offer",(data) => {
        console.log("offer:", client.id)
        clientWebrtcMap.forEach((value,key) => {
            value.emit('offer',data)
        })
    })
    client.on("answer",(data) => {
        console.log("answer:",client.id)
        clientWebrtcMap.forEach((value,key) => {
            value.emit('answer',data)
        })
    })
    client.on("iceCandidate",(data) => {
        console.log("iceCandidate:",client.id)
        clientWebrtcMap.forEach((value,key) => {
            value.emit('iceCandidate',data)
        })
    })
    client.on('event',(data) => {
       console.log("event:" ,JSON.stringify(data),token)
        clientWebrtcMap.forEach((value,key) => {
            value.emit('event',data)
        })
    })

    client.on('disconnect', () => {
        clientWebrtcMap.delete(client.id)
        console.log("已断开:", client.id)
    });
});

server.listen(8089, () => {
    console.log('App listening at port 8089')
})
